package br.edu.ufcg.fpc.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class Util {

	public static String readFromFile(File file) {
		String content = "";
		try {
			BufferedReader fileReader = new BufferedReader(new FileReader(file));
			while (fileReader.ready()) {
				content += fileReader.readLine() + "\n";
			}
			if (!content.isEmpty()) {
				content = content.substring(0, content.lastIndexOf("\n"));
			}
			fileReader.close();
		} catch (FileNotFoundException e) {
			content = null;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return content;
	}
	
	public static void writeToFile(File file, String content) {
		try {
			BufferedWriter fileWriter = new BufferedWriter(new FileWriter(file));
			if (content != null)
				fileWriter.write(content);
			fileWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
	
	public static Integer toInteger(String argument) {
		Integer i = null;
		try {
			i = Integer.parseInt(argument);
		} catch (NumberFormatException e) {
		}
		return i;
	}
	
	public static double calculateMean(List<Double> values) {
		// find the mean (average) of the data
		double average = 0;
		double size = values.size();
		
		for (int i=0; i < size; i++)
			average = average + values.get(i);

		average = average / size;
	
		return average;
	}

	public static double calculateStandardDeviation(List<Double> values, double average) {
		// find the standard deviation
		double numerator = 0;
		double size = values.size();

		for (int i=0; i < size; i++)
			numerator = numerator + Math.pow((values.get(i) - average), 2);

		double standardDeviation = Math.sqrt (numerator/size);
		
		return standardDeviation;
	}
	
}
